package com.dhecp.project.storage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dhecp.project.storage.domain.AssemblyMaintain;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.mapper.AssemblyMaintainMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.storage.domain.PurchaseStorage;
import com.dhecp.project.storage.mapper.PurchaseStorageMapper;
import com.dhecp.project.storage.service.PurchaseStorageService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 采购入库 服务实现层
 * @author: hlf
 * @create: 2022-09-01 10:43
 */
@Service
public class PurchaseStorageServiceImpl extends BaseModuleServiceImpl implements PurchaseStorageService {


    @Autowired
    private PurchaseStorageMapper storageMapper;
    @Autowired
    private AssemblyMaintainMapper maintainMapper;
    @Autowired
    private StockControlMapper stockControlMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.PurchaseStorage
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public PurchaseStorage queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchaseStorage> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public PurchaseStorage queryByGuid(String guid) {
        return storageMapper.findByGuid(guid);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchaseStorage> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.select(params);
    }

    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchaseStorage> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.selectGroup(params);
    }

    /**
     * @Description: 查询采购订单数据
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchaseStorage> selectOrderData(Map<String, Object> params) throws Exception {
        return storageMapper.selectOrderData(params);
    }

    /**
     * @Description: 查询线下采购订单数据
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchaseStorage> selectOfflineOrderData(Map<String, Object> params) throws Exception {
        return storageMapper.selectOfflineOrderData(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new PurchaseStorage());

        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<PurchaseStorage> businessDataList = (List<PurchaseStorage>) ajaxResult.get("businessDataList");


        List<RecordCheck> guidMapList = storageMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (businessDataList == null || businessDataList.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            for (PurchaseStorage businessData : businessDataList) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                } else {
                    guid = businessData.getGuid().toString();
                }
                businessData.setGuid(guid);
                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }

                if (guidMap.get(guid) == null) {
                    businessData.setCreateTime(new Date());
                    storageMapper.insert(businessData);
                } else {
                    storageMapper.update(businessData);
                    guidMap.remove(guid);
                }

            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                storageMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<PurchaseStorage> businessDataList = JSON.parseArray(params.get("infoItems").toString(), PurchaseStorage.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (PurchaseStorage businessData : businessDataList) {
            storageMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            storageMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchaseStorage> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchaseStorage businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchaseStorage> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchaseStorage businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 修改审核状态
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-08 9:15
     */
    @Override
    public AjaxResult updateType(Map<String, Object> params) {
        Integer x = 0;
        String msg = "";
        List<PurchaseStorage> purchaseStorages = JSON.parseArray(params.get("infoItems").toString(), PurchaseStorage.class);
        for (PurchaseStorage item : purchaseStorages
        ) {
            if (!item.getState().equals("未入库")) {
                PurchaseStorage purchaseStorage = storageMapper.findByGuid(item.getGuid());
                AssemblyMaintain assemblyMaintain = new AssemblyMaintain(); //获取组装方案
                assemblyMaintain = maintainMapper.findByProductID(purchaseStorage.getpCode());
                //获取库存信息
                List<StockControl> stockControl = stockControlMapper.findByRKBid(purchaseStorage.getBid());
                if (stockControl.size()>0){
                    for (StockControl item2:stockControl
                         ) {
                        item2.setvHw(item.getGoodsAllocation());//货位编码
                        item2.setvKq(item.getGoodsArea());//库区
                        item2.setgDepot(item.getWarehouseAddress());//所在仓库
                        item.setUpdateTime(new Date());
                        stockControlMapper.update(item2);//修改库存库区信息
                    }
                }
                if (assemblyMaintain != null) {
                    item.setUpdateTime(new Date());
                    item.setAuditor(ShiroUtils.getUserId());
                    item.setvZzZt("未组装");
                    storageMapper.update(item);
                } else {
                    x++;
                }
                if (x > 0) {
                    msg = x + "条数据审核失败，请确认组装方案是否已维护！";
                }
            } else {
                storageMapper.update(item);
            }
        }
        return AjaxResult.success("操作成功!" + msg);
    }


    /**
     * @Description: 导入
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-08 9:15
     */
    @Override
    public AjaxResult saveImportData(Map<String, Object> params) {

        List<PurchaseStorage> purchaseStorageList = JSON.parseArray(params.get("infoItems").toString(), PurchaseStorage.class);
        if (purchaseStorageList == null || purchaseStorageList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        int x = 0;
        for (PurchaseStorage item : purchaseStorageList) {

            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("trackingNumber", item.getTrackingNumber());
            List<PurchaseStorage> purchaseStorages = storageMapper.findByBID(params2);

            if (purchaseStorages.size() > 0) {
                for (PurchaseStorage item2 : purchaseStorages
                ) {
                    item.setAuditor(ShiroUtils.getUserId());
                    item2.setUpdateTime(new Date());
                    item2.setState("已入库");
                    item.setvZzZt("未组装");
                    storageMapper.update(item2);
                }
            }
            x++;
        }
        return AjaxResult.success(x + "条数据导入成功");
    }

}